package com.spring.boot.service;

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Redis 管道技术使用
 *
 * @author LiKun
 * @date 2021/10/25 15:33
 */
@Service
public class PipelineService {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 存入和获取的序列化方式必须一样，否则可能取不到数据
     *
     * @param map 数据集
     *
     * @return 数据集
     */
    public List<String> batchPushData(Map<String, String> map) {
        System.out.println(redisTemplate.opsForValue().get("one"));

        List<String> result = new ArrayList<>(4);
        redisTemplate.executePipelined(new SessionCallback<String>() {

            @Override
            public <K, V> String execute(RedisOperations<K, V> redisOperations) throws DataAccessException {
                final ValueOperations<String, String> opsForValue = (ValueOperations<String, String>) redisOperations.opsForValue();
                map.forEach(opsForValue::set);

                return null;
            }

        });
        System.out.println(redisTemplate.opsForValue().get("one"));

        return result;
    }

}
